package com.fpswork.util;

import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.fpswork.common.Constant;
import com.fpswork.core.exception.exception.BusinessException;
public class StringUtil {
	/**
	 * 获取uuid
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "") ;
	}
	/**
	 * 文本域保存数据时，保存空格和回车
	 */
    public static String turn(String str) {  
        while (str.indexOf("\n") != -1) {  
            str = str.substring(0, str.indexOf("\n")) + "<br>"  
                    + str.substring(str.indexOf("\n") + 1);  
        }  
        while (str.indexOf(" ") != -1) {  
            str = str.substring(0, str.indexOf(" ")) + "&nbsp"  
                    + str.substring(str.indexOf(" ") + 1);  
        }  
        return str;  
    } 
	/**
	 * 文本域展示数据时，替换回去
	 */
    public static String isturn(String str) {  
        while (str.indexOf("<br>") != -1) {  
            str = str.substring(0, str.indexOf("<br>")) + "\n"  
                    + str.substring(str.indexOf("<br>") + 4);  
        }  
        while (str.indexOf("&nbsp") != -1) {  
            str = str.substring(0, str.indexOf("&nbsp")) + " "  
                    + str.substring(str.indexOf("&nbsp") + 5);  
        }  
        return str;  
    } 
	/**
	 * MD5加密字符串
	 */
	public static String toMD5(String plainText)throws BusinessException{
		String str="";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) i += 256;
				if (i < 16) buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			str = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new BusinessException(e);
		}
		return str;
	}
	 // 加密后解密   
	 public   static  String jmMd5(String inStr) {  
	  char [] a = inStr.toCharArray();  
	  for  ( int  i =  0 ; i < a.length; i++) {  
	   a[i] = (char ) (a[i] ^  't' );  
	  }  
	  String k = new  String(a);  
	  return  k;  
	 }  

    /** 
     * 将字符串中的半个汉字转为'  ' 
     * @param str 要转换的包含半个汉字的任意字符串 
     * @return  转换之后的字符串 
     */ 
    public static String formatString(String str){
        char[] c = str.toCharArray(); 
        StringBuffer sb=new StringBuffer("");
        for (int index = 0; index < c.length; index++) { 
            if ((0 >(int)c[index]||(int)c[index]> 127)&&(str.substring(index, index+1).getBytes().length==1)) {
            	sb.append("  ");
            } else {
            	sb.append(c[index]);
            } 
        } 
        return sb.toString();
    } 
    

	
	/** 
     * Returns a String with all occurrences of the String from * replaced by the String to. 
     * 字符串替换,返回一个经过替换的字符串.
     * 
     * @param        in     待替换的字符串
     * @param        from   替换目标
     * @param        to     替换为
     * @param        is     是否区分大小写
     * @return The new String    替换后的字符串
	 * @throws BusinessException 业务错误
     **/
	 public static String replaceString(String in, String from, String to,boolean is) throws BusinessException{
		if(in==null){throw new BusinessException("字符串替换错误,待替换字符串不能为Null!");} 
		if(from==null||"".equals(from)){throw new BusinessException("字符串替换错误,替换目标不能为Null或空串!");} 
		StringBuffer sb = new StringBuffer(in.length() * 2); 
		String posString = in; 
		String cmpString = from;
		if(!is){
		 posString = in.toLowerCase(); 
		 cmpString = from.toLowerCase();
		}
	    int i = 0; 
	    boolean done = false;
		while (i < in.length() && !done) {
			 int start = posString.indexOf(cmpString, i);
			 if (start == -1) { 
				 done = true;
			 } else { 
				 sb.append(in.substring(i, start) + to);
				 i = start + from.length(); 
			} 
		}
		if (i < in.length()) {	 	 
			sb.append(in.substring(i)); 
   	 } 
		return sb.toString(); 
	}
	 
    /** 
     * 返回字符串中出现目标字符串的个数.
     * 
     * @param        in       待替换的字符串
	 * @param        target   目标
	 * @param        is       是否区分大小写
	 * @return int                 出现次数
	 * @throws BusinessException   业务错误
     **/
	 public static int countString(String in, String target,boolean is) throws BusinessException{
		if(in==null){throw new BusinessException("字符串替换错误,待替换字符串不能为Null!");}
		if(target==null||"".equals(target)){throw new BusinessException("字符串替换错误,替换目标不能为Null或空串!");}
		String posString = in;
		String cmpString = target;
		if(!is){
			posString = in.toLowerCase();
			cmpString = target.toLowerCase();
		}
		int i = 0;
		int count=0;
		boolean done = false;
		while (i < in.length() && !done) {
			 int start = posString.indexOf(cmpString, i);
			 if (start == -1) {
				 done = true;
			 } else {
				 count++;
				 i = start + target.length();
			}
		}
		if (i < in.length()) {}
		return count;
	 }
	 
	/**
	 * 分割符字符串中参数的个数
	 * @param  str               分隔符数据包
	 * @param  separator        分隔符
	 * @return int               int
	 **/
	public static int splitStringParas(String str, String separator) throws BusinessException{
		int number = 0;
		String indexStr;
		int index = 0, seplen = 0;
		try{
			if ((str == null) || (str.length() == 0) || (separator == null) || (separator.length() == 0))return 0;
			seplen = separator.length();
			indexStr = str;
			index = indexStr.indexOf(separator);
			while (index != -1) {
				number = number + 1;
				indexStr = indexStr.substring(index + seplen);
				index = indexStr.indexOf(separator);
			}
			if (indexStr != null && indexStr.length() != 0) {
				number = number + 1;
			}
			return number;
		}catch (Exception e) {
			throw new BusinessException(e);
		}
	}

	/**
	 * 分解分割符字符串中的参数，以字符串数组形式返回
	 * @param  str               分隔符数据包
	 * @param  separator         分隔符
	 * @return List              ArrayList
	 **/
	public static List<String> splitString(String str, String separator)  throws BusinessException{
		ArrayList<String> StrList = new ArrayList<String>();
		String indexStr;
		int index = 0, seplen = 0;

		try{
			if ((str == null) || (str.length() == 0) || (separator == null) ||
				(separator.length() == 0))return StrList;

			seplen = separator.length();
			indexStr = str;
			index = indexStr.indexOf(separator);
			while (index != -1) {
				if(indexStr.substring(0, index)==null){StrList.add("");}
				else{StrList.add(indexStr.substring(0, index));}
				indexStr = indexStr.substring(index + seplen);
				index = indexStr.indexOf(separator);
			}
			if (indexStr != null && indexStr.length() != 0) {
				StrList.add(indexStr);
			}
			return StrList;
		}
		catch (Exception e) {
			throw new BusinessException(e);
		}
	}
	    
	    
	/**
	 * 分解分割符字符串中的参数，返回指定位置的字符串
	 * @param  str                分隔符数据包
	 * @param  separator         分隔符
	 * @param  position          取值位置
	 * @return String             目标字符串
	 **/
	public static String splitString(String str, String separator,int position)  throws BusinessException{
		ArrayList<String> StrList = new ArrayList<String>();
		String indexStr;
		int index = 0, seplen = 0;
		if(position<=0){position=1;}
		try{
			if ((str == null) || (str.length() == 0) || (separator == null) ||
				(separator.length() == 0))return "";
			seplen = separator.length();
			indexStr = str;
			index = indexStr.indexOf(separator);
			while (index != -1) {
				if(indexStr.substring(0, index)==null){StrList.add("");}
				else{StrList.add(indexStr.substring(0, index));}
				indexStr = indexStr.substring(index + seplen);
				index = indexStr.indexOf(separator);
			}
			if (indexStr != null && indexStr.length() != 0) {
				StrList.add(indexStr);
			}
			if(StrList.size()>=position){
				return StrList.get(position-1);
			}else{
				return "";
			}
		}
		catch (Exception e) {
			throw new BusinessException(e);
		}
	}
	 
	/**
	 * 按字节位置截取字符串
	 * @param  value             原字符串
	 * @param  start             开始位置(从1开始)
	 * @param  end               结束位置
	 * @return String            截取字符串
	 **/
	public static String getStringByBytes(String value,int start,int end){
		int length=end-start+1;
		byte[] bytes=value.getBytes();
		Class<?> x=bytes.getClass();
		Class<?> cc=x.getComponentType();
		Object newArray=Array.newInstance(cc,length);
		System.arraycopy(bytes, start-1, newArray, 0, length);
		return new String((byte[])newArray);
	}
		
	/**
	 * 字符串左补齐操作（按字节操作 byte）
	 * @param  in                原字符串
	 * @param  size              补齐长度
	 * @param  c                 补齐使用字符
	 * @return String            返回字符串
	 **/
	public static String fillLeftByBytes(String in,int size,String c) throws BusinessException{
		int length=0;
		byte[] bytes=null;
		if(in==null){in="";}
		length=size-in.getBytes().length;
		if(length<0){
			throw new BusinessException("字符串左补齐操作错误,字符串（"+in+"）超过规定长度("+size+")");
		}else if(length==0){
			return in;
		}else{
			if(c==null||"".equals(c)){
				c=" ";
			}else{
				c=c.substring(0, 1);
			}
			bytes=c.getBytes();
			Byte b=bytes[0];
			Class<?> x=bytes.getClass();
			Class<?> cc=x.getComponentType();
			Object newArray=Array.newInstance(cc,length);
			bytes=(byte[])newArray;

			for(int i=0;i<size-in.getBytes().length;i++){
				bytes[i]=b;
			}
		}
		return new String(bytes)+in;
	}
		
	/**
	 * 字符串右补齐操作（按字节操作 byte）
	 * @param  in                原字符串
	 * @param  size              补齐长度
	 * @param  c                 补齐使用字符
	 * @return String            返回字符串
	 **/
	public static String fillRightByBytes(String in,int size,String c) throws BusinessException{
		int length=0;
		byte[] bytes=null;
		if(in==null){in="";}
		length=size-in.getBytes().length;
		if(length<0){
			throw new BusinessException("字符串左补齐操作错误,字符串（"+in+"）超过规定长度("+size+")");
		}else if(length==0){
			return in;
		}else{
			if(c==null||"".equals(c)){
				c=" ";
			}else{
				c=c.substring(0, 1);
			}
			bytes=c.getBytes();
			Byte b=bytes[0];
			Class<?> x=bytes.getClass();
			Class<?> cc=x.getComponentType();
			Object newArray=Array.newInstance(cc,length);
			bytes=(byte[])newArray;

			for(int i=0;i<size-in.getBytes().length;i++){
				bytes[i]=b;
			}
		}
		return  in+new String(bytes);
	}
		

	/**
	 * 字符串左补齐操作
	 * @param  in                原字符串
	 * @param  size              补齐长度
	 * @param  c                 补齐使用字符
	 * @return String            返回字符串
	 **/
	public static String fillLeft(String in,int size,String c) throws BusinessException{
		String newString="";
		if(in==null){in="";}
		if(c==null||"".equals(c)){
			c=" ";
		}else{
			c=c.substring(0, 1);
		}
		if(in.length()>size){
			throw new BusinessException("字符串左补齐操作错误,字符串（"+in+"）超过规定长度("+size+")");
		}else if(in.length()==size){
			return in;
		}else{
			for(int i=0;i<size-in.length();i++){
				newString=newString+c;
			}
		}
		return newString+in;
	}

	/**
	 * 字符串右补齐操作
	 * @param  in                原字符串
	 * @param  size              补齐长度
	 * @param  c                 补齐使用字符
	 * @return String            返回字符串
	 **/
	public static String fillRight(String in,int size,String c) throws BusinessException{
		String newString="";
		if(in==null){in="";}
		if(c==null||"".equals(c)){
			c=" ";
		}else{
			c=c.substring(0, 1);
		}
		if(in.length()>size){
			throw new BusinessException("字符串右补齐操作错误,字符串（"+in+"）超过规定长度("+size+")");
		}else if(in.length()==size){
			return in;
		}else{
			for(int i=0;i<size-in.length();i++){
				newString=newString+c;
			}
		}
		return in+newString;
	}
		
	/**
	* 判断是否为空串""
	*/
	public static boolean isEmpty(String sValue) {
		if(sValue==null) return true;
		return sValue.trim().equals("") ? true : false ;
	}

	/**
	 * 判断是否为空串""
	 */
	public static boolean isNotEmpty(String sValue) {
		 return !isEmpty(sValue);
	}


	public static boolean isNumeric(String str) {
		if(str == null) {
			return false;
		} else {
			int sz = str.length();

			for(int i = 0; i < sz; ++i) {
				if(!Character.isDigit(str.charAt(i))) {
					return false;
				}
			}

			return true;
		}
	}

	public static boolean isNumericSpace(String str) {
		if(str == null) {
			return false;
		} else {
			int sz = str.length();

			for(int i = 0; i < sz; ++i) {
				if(!Character.isDigit(str.charAt(i)) && str.charAt(i) != 32) {
					return false;
				}
			}

			return true;
		}
	}

	public static boolean isWhitespace(String str) {
		if(str == null) {
			return false;
		} else {
			int sz = str.length();

			for(int i = 0; i < sz; ++i) {
				if(!Character.isWhitespace(str.charAt(i))) {
					return false;
				}
			}

			return true;
		}
	}
		  
	public static String joinString(List<String> list,String separator) throws BusinessException{
		try{
			if(separator==null){
				separator="";
			}
			String value="";
			if(list!=null&&!list.isEmpty()){
				for(int i=0;i<list.size();i++){
					String temp=list.get(i);
					value=value+temp+separator;
				}
			}
			return value;
		}catch(Exception e){
			throw new BusinessException(e);
		}
	}
		  
	
	public final static String toString(java.sql.Date value,String dateFormat) throws BusinessException {
		if(StringUtil.isEmpty(dateFormat)){
			dateFormat= Constant.FORMAT_DATETIME;
		}
		if(value==null){return null;}
		else{
			return new SimpleDateFormat(dateFormat).format(value);
		}

	}

	public final static String toString(Date value,String dateFormat) throws BusinessException {
		if(StringUtil.isEmpty(dateFormat)){
			dateFormat= Constant.FORMAT_DATETIME;
		}
		if(value==null){return null;}
		else{
			return new SimpleDateFormat(dateFormat).format(value);
		}
	}
	public static String nullReturnStar(String str){ 
		if(null != str && !"".equals(str)){
			return filterHtml(str);
		}
		return "*";
	}
	
	
	
	public static String arrayReturnString(String str[],int i){ 
		if(null == str ){
			return "";
		}
		try {
			
			if(i > str.length -1){
				return "";
			}
			
			return str[i].trim();
		} catch (Exception e) {
			return "";
		}
	}
	
	
	public static Double arrayReturnDouble(String str[],int i){ 
		if(null == str ){
			return 0d;
		}
		try {
			String t = arrayReturnString(str,i);
			if("".equals(t)){
				return 0d;
			}
			return Double.parseDouble(t);
		} catch (Exception e) {
			return 0d;
		}
	}
	
	public static int arrayReturnInt(String str[],int i){ 
		if(null == str ){
			return 0;
		}
		try {
			String t = arrayReturnString(str,i);
			if("".equals(t)){
				return 0;
			}
			return Integer.parseInt(t);
		} catch (Exception e) {
			return 0;
		}
	}
	
	
	public static String intReturnStringZero(String str){ 
		if(null == str ){
			return "0";
		}
		try {
			str = str.split("\\.")[0];
			return str;
		} catch (Exception e) {
			return "0";
		}
	}
	
	public static String intReturnStringOne(String str){ 
		if(null == str ){
			return "1";
		}
		try {
			str = str.split("\\.")[0];
			return str;
		} catch (Exception e) {
			return "1";
		}
	}
	
	public static String intReturnStringSpec(Integer val){ 
		if(null == val ){
			return "";
		}
		try {
			return String.valueOf(val);
		} catch (Exception e) {
			return "";
		}
	}
	
	
	public static String doubleReturnStringZero(String str){ 
		if(null == str ){
			return "0.0";
		}
		try {
			Double   d   =   Double.valueOf(str);  
			DecimalFormat df = new DecimalFormat("##.00"); 
			return df.format(d); 
		} catch (Exception e) {
			return "0.0";
		}
	}
	
	public static String doubleReturnStringSpec(String str){ 
		if(null == str ){
			return "";
		}
		try {
			Double   d   =   Double.valueOf(str);  
			DecimalFormat df = new DecimalFormat("##.00"); 
			return df.format(d); 
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String doubleReturnStringSpec(Double   d ){ 
		if(null == d ){
			return "";
		}
		try {
			DecimalFormat df = new DecimalFormat("##.00"); 
			return df.format(d); 
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String nullReturnSpace(String str){ 
		if(null != str && !"".equals(str)){
			return filterHtml(str);
		}
		return "";
	}	

	public static String filterHtml2(String input) {
		if (input == null) {
			return null;
		}
		if (input.length() == 0) {
			return input;
		}
		input = input.replaceAll("<", "");
		input = input.replaceAll(">", ">");
		input = input.replaceAll("'", "‘"); 
		input = input.replaceAll("\"", "“"); 
		return input;
		
	}
	
	public static String filterHtml(String input) {
		if (input == null) {
			return null;
		}
		if (input.length() == 0) {
			return input;
		}
		//input = input.replaceAll("&", "&amp;");
		input = input.replaceAll("<", "&lt;");
		input = input.replaceAll(">", "&gt;");
		//input = input.replaceAll(" ", "&nbsp;");
		input = input.replaceAll("'", "‘"); 
		input = input.replaceAll("\"", "”");
		return input;//.replaceAll("\n", "<br/>");
		
	}
	
	public static String csvHandlerStr(String str) {  
        //csv格式如果有逗号，整体用双引号括起来；如果里面还有双引号就替换成两个双引号      
        String tempDescription = str;  
        if(null == tempDescription){
        	return "";
        }
        if(null != str && !"".equals(str) && str.contains(",")){                
            if(str.contains("\"")){  
                tempDescription = str.replace("\"", "\"\"");  
            }  
            tempDescription = "\""+tempDescription+"\"";  
        }  
        return tempDescription;  
	}  
	
	
	public static String  arrayToStr(String [] array){
		String str =  "";	
		if(null != array  && array.length >0 ){
			for(String s : array){
				if(null != s && !"".equals(s.trim())){
					if("".equals(str) ){
						str = s;
					}else{
						str = str + "," + s.trim();
					}
				}
			}
		}
		return str;
	}
	
	public static String  arrayToInQuery(String [] array){
		String str =  "";	
		if(null != array  && array.length >0 ){
			for(String s : array){
				if(null != s && !"".equals(s.trim())){
					if("".equals(str) ){
						str = "'"+s.trim()+"'";
					}else{
						str = str + ",'"+s.trim()+"'";
					}
				}
			}
		}
		return str;
	}
	
	public static String  listToInQuery(List<String> array){
		String str =  "";	
		if(null != array  && array.size() >0 ){
			for(String s : array){
				if(null != s && !"".equals(s.trim())){
					if("".equals(str) ){
						str = "'"+s.trim()+"'";
					}else{
						str = str + ",'"+s.trim()+"'";
					}
				}
			}
		}
		return str;
	}
	
	public static List<String> mergeArrayToList(String[] array1 ,String[] array2){
		List<String> list = new ArrayList<String>() ;
		if(null != array1 && array1.length >0 ){
			for(String str : array1 ){
				if(null != str && !"".equals(str)){
					list.add(str);
				}
			}
		}
		
		if(null != array2 && array2.length >0 ){
			for(String str : array2 ){
				if(null != str && !"".equals(str)){
					list.add(str);
				}
			}
		}
		
		if(list.size()>0){
			return list;
		}
		return null;
		
		
	}
	
	
	public static String objectToStr(Object obj){
		if(null != obj){
			return obj.toString();
		}
		return "";
	}
	
	public static String sqlField(int length){
		String field = "?";
		for(int i = 1 ; i < length; i ++ ){
			field = field + ",?";
		}
		return "values("+field+")"; 
	}
	
}

